import React, {useState} from 'react';
import {useModel} from 'umi';
import {UploadOutlined, UserOutlined} from '@ant-design/icons';
import {Button, Input, Upload, message, Form, Avatar, Image} from 'antd';
import ProForm, {
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { currentUser, editAdminUser } from '@/services/ant-design-pro/api';


import styles from './BaseView.less';

const BaseView = () => {

  const [avatar, setAvatar] = useState();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(undefined)
  const { initialState, setInitialState } = useModel('@@initialState');

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async () => {
    const res = await currentUser();
    // 处理地区
    setAvatar(res.data.avatar);
    setLoading(false)
    return res.data;
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/18 17:32:00
   * 功能：提交按钮
   */
  const handleSubmit = async (values) => {
    const data = values;
    const res = await editAdminUser(data);
    if (res.code === 200) {
      message.success(res.msg);
      initialState.currentUser = {...res.data}
      initialState.currentUser.avatar = avatar
      setInitialState((s) => ({ ...s, initialState }));
    }
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/19 16:07:41
   * 功能：头像配置
   */
  const avatarProps = {
    name: 'avatar_file',
    action: '/admin/AdminUserCenter/avatar',
    headers: {
      AdminToken: localStorage.getItem('access_token') || '',
    },
    accept: '.jpg,.png,.jpeg',
    showUploadList: false,
    beforeUpload(file) {
      if (file.size > 102400) {
        message.warning('图片不可大于100k~');
        return false;
      }
    },
    onChange(info) {
      if (info.file.status === 'done') {
        let res = info.file.response;
        if (res.code == 200) {
          message.success('头像上传成功~');
          setAvatar(res.data.avatar);
          initialState.currentUser.avatar = res.data.avatar
          setInitialState((s) => ({ ...s, initialState }));
        } else {
          message.error(res.msg);
        }
      } else if (info.file.status === 'error') {
        message.error('头像上传失败！');
      }
    },
  };

  /**
   * 作者：糜家智
   * 时间：2022/5/11
   * 功能：头像组件
   */
  function avatarPro() {
    return (
      <Form.Item label="头像">
          <div className={styles.avatar}>

            <Avatar
              size={120}
              icon={<UserOutlined />}
              src={avatar}
              onClick={() => setVisible(true)}
            />

            <Image
              width={200}
              style={{ display: 'none' }}
              preview={{
                visible,
                src: avatar,
                onVisibleChange: (value) => {
                  setVisible(value);
                },
              }}
            />

          </div>

          <Upload {...avatarProps}>
            <Button className={styles.btnUpload} icon={<UploadOutlined />}>
              更换头像
            </Button>
          </Upload>

          <span className={styles.desc}>jpg、png图片，小于200KB，宽高1:1</span>
      </Form.Item>
    );
  }

  return (
    <div className={styles.baseView}>
      {loading ? null : (
        <>
          <div className={styles.left}>
            <ProForm
              onFinish={(values) => handleSubmit(values)}
              request={() => getData()}
              layout="vertical"
              submitter={{
                resetButtonProps: {
                  style: {
                    display: 'none',
                  },
                },
                submitButtonProps: {
                  children: '更新基本信息',
                },
              }}
              hideRequiredMark
            >

              <ProFormText width="md" name="username" label="账号" rules={[{required: true, message: '请输入您的账号!',}]}/>
              <ProFormText width="md" name="nickname" label="昵称" rules={[{required: true, message: '请输入您的昵称!',}]}/>

              <Form.Item
                name="phone"
                label="手机"
                rules={[
                  {
                    max: 11,
                    message: '请输入正确的手机号',
                    pattern: /^1[3456789]\d{9}$/,
                  },
                ]}
              >
                <Input placeholder="请输入手机" maxLength={11} />
              </Form.Item>

              <ProFormText
                name="email"
                label="邮箱"
                placeholder="请输入邮箱"
                rules={[
                  { type: 'email', message: '邮箱格式不对' },
                ]}
              />

              <ProFormTextArea name="desc" label="个人简介" placeholder="个人简介" />

            </ProForm>

          </div>

          <div className={styles.right}>
            {avatarPro()}
          </div>
        </>
      )}
    </div>
  );
};

export default BaseView;
